﻿using System;
using System.Net;
using System.Web.Mvc;
using Matrix.Common.Utility;
using Matrix.MaKaYunShang.BLL;
using Matrix.MaKaYunShang.Model;
using System.Linq;
using Matrix.MaKaYunShang.Model.Dto;

namespace Matrix.MaKaYunShang.MagWeb.Controllers
{
    [Authorization]
    [Matrix.MaKaYunShang.Model.Attributes.Skip]
    public class SysConfigController : BaseController
    {
        public ActionResult Detail()
        {
            var model = SysConfigBLL.Instance.GetModel(1) ?? new SysConfig();
            if (model.Id > 0)
            {
                model.TimeToCancelPayOrder = model.TimeToCancelPayOrder / 60;
                model.OrderMsgMcAlertInterval = model.OrderMsgMcAlertInterval / 60;
                model.OrderGrapTimeLength = model.OrderGrapTimeLength / 60;
            }
            return View(model);
        }

        [HttpPost]
        public JsonResult Save(SysConfig model)
        {
            var result = new Result();
            if (model != null)
            {
                model.UpdateTime = DateTime.Now;
                model.TimeToCancelPayOrder = model.TimeToCancelPayOrder * 60;
                model.OrderMsgMcAlertInterval = model.OrderMsgMcAlertInterval * 60;
                model.OrderGrapTimeLength = model.OrderGrapTimeLength * 60;
                var tempModel = SysConfigBLL.Instance.GetModel(1);
                if (tempModel == null)
                {
                    result.Status = SysConfigBLL.Instance.Add(model) > 0;
                }
                else
                {
                    model.Id = tempModel.Id;
                    result.Status = SysConfigBLL.Instance.Update(model);
                }
            }
            if (result.Status == false && string.IsNullOrEmpty(result.Message))
            {
                result.Message = "保存失败，请重试！";
            }
            return Json(result);
        }
        public ActionResult SysMoney()
        {
            return View(SysMoneyBLL.Instance.GetModelList().FirstOrDefault() ?? new SysMoney());
        }

        [HttpPost]
        public JsonResult SysMoney(SysMoney model)
        {
            var result = new Result();
            if (model != null)
            {
                model.UpdateTime = DateTime.Now;
                var tempModel = SysMoneyBLL.Instance.GetModelList().FirstOrDefault();
                if (tempModel == null)
                {
                    result.Status = SysMoneyBLL.Instance.Add(model) > 0;
                }
                else
                {
                    model.Id = tempModel.Id;
                    result.Status = SysMoneyBLL.Instance.Update(model);
                }
            }
            if (result.Status == false && string.IsNullOrEmpty(result.Message))
            {
                result.Message = "保存失败，请重试！";
            }
            return Json(result);
        }
        public ActionResult SysPayDiscountConfig(int id = 0)
        {
            return View(SysPayDiscountConfigBLL.Instance.GetModel(id) ?? new SysPayDiscountConfig());
        }

        [HttpPost]
        public JsonResult SysPayDiscountConfig(SysPayDiscountConfig model)
        {
            var result = new Result();
            if (model != null)
            {
                //var sysPayDiscountConfig=   SysPayDiscountConfigBLL.Instance.GetModel(model.MinPayDiscount,model.MaxPayDiscount);
                //   if (sysPayDiscountConfig != null)
                //   {
                //       result.Status = false;
                //       result.Message = "立减金额列表中已经存在!";
                //       return Json(result);
                //   }
                var tempModel = SysPayDiscountConfigBLL.Instance.GetModel(model.Id);
                if (tempModel == null)
                {
                    result.Status = SysPayDiscountConfigBLL.Instance.Add(model) > 0;
                }
                else
                {
                    model.Id = tempModel.Id;
                    result.Status = SysPayDiscountConfigBLL.Instance.Update(model);
                }
            }
            if (result.Status == false && string.IsNullOrEmpty(result.Message))
            {
                result.Message = "保存失败，请重试！";
            }
            return Json(result);
        }

        #region new 系统立减规则

        public ActionResult DiscountBase()
        {
            return View();
        }
        [HttpPost]
        public ActionResult DiscountBaseListing(int draw, int start, int length)
        {
            try
            {
                int order;
                int.TryParse(Request["order[0][column]"], out order);
                string direction = Request["order[0][dir]"];
                var orderByColumns = new[] { "Title", "TimeSpanType", "TimeSpanCount", "ConsumerTotalTimes", "UserType" };
                string search = Request["search[value]"];
                TableDataViewDto<ViewDiscountBaseDto> theList = DiscountBaseBLL.Instance.GetPagingList(draw, (start / length) + 1, length, SqlSafe(search),
                orderByColumns[order] + " " + direction);
                JsonResult jsonResult = Json(theList);
                jsonResult.MaxJsonLength = int.MaxValue;
                return jsonResult;
            }
            catch (Exception ex)
            {
                Logger.Error("Coupon Listing Catch Error: " + ex.Message);
                return Json(false);
            }
        }

        public ActionResult SysPayDiscountCreate()
        {
            return View();
        }
        [HttpPost]
        public ActionResult SysPayDiscountCreate(DiscountBase model, FormCollection collection)
        {
            var result = new Result() { Message = "添加失败", Status = false };
            if (model == null)
            {
                return Json(result);
            }
            var discountBaseItem = DiscountBaseBLL.Instance.GetModelList(string.Format("  UserType={0}", model.UserType)).FirstOrDefault();
            if (discountBaseItem != null)
            {
                result.Message = "用户类型规则已经存在,添加失败";
                return Json(result);
            }
            DiscountBase discountBase = new DiscountBase()
            {
                TimeSpanCount = model.TimeSpanCount,
                ConsumerTotalTimes = model.ConsumerTotalTimes,
                UserType = model.UserType,
                IsDelete = false,
                Title = model.Title,
                TimeSpanType = model.TimeSpanType
            };
            var resultId = DiscountBaseBLL.Instance.Add(discountBase);
            if (resultId < 1)
            {
                return Json(result);
            }
            // DiscountTimesProbabilityBLL.Instance.Delete(resultId);
            if (!string.IsNullOrEmpty(model.DiscountPercentStr))
            {
                int[] discountPercent = model.DiscountPercentStr.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();
                for (int i = 0; i < discountPercent.Length; i++)
                {
                    DiscountTimesProbability discountTimesProbability = new DiscountTimesProbability()
                    {
                        DiscountBaseId = resultId,
                        DiscountPercent = discountPercent[i],
                        SerialNum = i + 1,
                        IsDelete = false
                    };
                    DiscountTimesProbabilityBLL.Instance.Add(discountTimesProbability);
                }
            }
            if (!string.IsNullOrEmpty(model.MinusConfigureStr))
            {
                string[] sysPayDiscountConfigA = model.MinusConfigureStr.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries).ToArray();
                foreach (var itema in sysPayDiscountConfigA)
                {
                    string[] sysPayDiscountConfigB = itema.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToArray();
                    SysPayDiscountConfig sysPayDiscountConfig = new SysPayDiscountConfig()
                    {
                        DiscountBaseId = resultId,
                        DiscountProbability = int.Parse(sysPayDiscountConfigB[2]),
                        IsDelete = false,
                        MaxPayDiscount = decimal.Parse(sysPayDiscountConfigB[1]),
                        MinPayDiscount = decimal.Parse(sysPayDiscountConfigB[0])
                    };
                    SysPayDiscountConfigBLL.Instance.Add(sysPayDiscountConfig);
                }
            }
            result.Status = true;

            return Json(result);
        }
        public ActionResult SysPayDiscountUpdate(int id)
        {
            var discountBase = DiscountBaseBLL.Instance.GetModel(id);
            if (discountBase == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
            }
            discountBase.SysPayDiscountConfigList = SysPayDiscountConfigBLL.Instance.GetModelList(string.Format("DiscountBaseId={0}", discountBase.Id));
            discountBase.DiscountTimesProbabilityList =
            DiscountTimesProbabilityBLL.Instance.GetModelList("  DiscountBaseId=" + discountBase.Id);
            return View(discountBase);
        }
        [HttpPost]
        public ActionResult SysPayDiscountUpdate(DiscountBase model)
        {
            var result = new Result() { Message = "修改失败", Status = false };
            if (model == null)
            {
                return Json(result);
            }
            var discountBase = DiscountBaseBLL.Instance.GetModel(model.Id);
            if (discountBase == null)
            {
                return Json(result);
            }
            if (model.UserType != discountBase.UserType)
            {
                var discountBaseItem = DiscountBaseBLL.Instance.GetModelList(string.Format("  UserType={0}", model.UserType)).FirstOrDefault();
                if (discountBaseItem != null)
                {
                    result.Message = "用户类型规则已经存在,添加失败";
                    return Json(result);
                }
            }
            discountBase.TimeSpanCount = model.TimeSpanCount;
            discountBase.ConsumerTotalTimes = model.ConsumerTotalTimes;
            discountBase.UserType = model.UserType;
            discountBase.Title = model.Title;
            discountBase.TimeSpanType = model.TimeSpanType;
            var isRsule = DiscountBaseBLL.Instance.Update(discountBase);
            if (isRsule == false)
            {
                return Json(result);
            }
            DiscountTimesProbabilityBLL.Instance.DeleteByDiscountBaseId(discountBase.Id);
            if (!string.IsNullOrEmpty(model.DiscountPercentStr))
            {
                int[] discountPercent = model.DiscountPercentStr.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();
                for (int i = 0; i < discountPercent.Length; i++)
                {
                    DiscountTimesProbability discountTimesProbability = new DiscountTimesProbability()
                    {
                        DiscountBaseId = discountBase.Id,
                        DiscountPercent = discountPercent[i],
                        SerialNum = i + 1,
                        IsDelete = false
                    };
                    DiscountTimesProbabilityBLL.Instance.Add(discountTimesProbability);
                }
            }
            SysPayDiscountConfigBLL.Instance.DeleteByDiscountBaseId(discountBase.Id);
            if (!string.IsNullOrEmpty(model.MinusConfigureStr))
            {
                string[] sysPayDiscountConfigA = model.MinusConfigureStr.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries).ToArray();
                foreach (var itema in sysPayDiscountConfigA)
                {
                    string[] sysPayDiscountConfigB = itema.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToArray();
                    SysPayDiscountConfig sysPayDiscountConfig = new SysPayDiscountConfig()
                    {
                        DiscountBaseId = discountBase.Id,
                        DiscountProbability = int.Parse(sysPayDiscountConfigB[2]),
                        IsDelete = false,
                        MaxPayDiscount = decimal.Parse(sysPayDiscountConfigB[1]),
                        MinPayDiscount = decimal.Parse(sysPayDiscountConfigB[0])
                    };
                    SysPayDiscountConfigBLL.Instance.Add(sysPayDiscountConfig);
                }
            }
            result.Status = true;
            return Json(result);
        }
        #endregion

        #region 列表页
        public ActionResult SysPayDiscountConfigList()
        {
            return View();
        }
        [HttpPost]
        public JsonResult SysPayDiscountConfigList(int draw, int start, int length)
        {
            try
            {
                int order;
                int.TryParse(Request["order[0][column]"], out order);
                string direction = Request["order[0][dir]"];
                var orderByColumns = new[] { "Id", "MinPayDiscount", "MaxPayDiscount", "DiscountProbability", "Action" };
                string search = Request["search[value]"];
                TableDataViewDto<ViewSysPayDiscountConfigDto> theList = SysPayDiscountConfigBLL.Instance.GetPagingList(draw, (start / length) + 1, length, SqlSafe(search),
                orderByColumns[order] + " " + direction);
                JsonResult jsonResult = Json(theList);
                jsonResult.MaxJsonLength = int.MaxValue;
                return jsonResult;
            }
            catch (Exception ex)
            {
                Logger.Error("SysConfigController SysPayDiscountConfigList Catch Error: " + ex.Message);
                return Json(false);
            }
        }

        [HttpPost]
        public JsonResult SysPayDiscountConfigDelete()
        {
            var ids = Request["doIds"];
            var result = SysPayDiscountConfigBLL.Instance.DeleteList(ids);
            return Json(result);

        }
        #endregion

        #region 项目管理

        public ActionResult ProjectInfo()
        {
            return View();
        }

        [HttpPost]
        public JsonResult ProjectInfoList(int draw, int start, int length)
        {
            try
            {
                int order;
                int.TryParse(Request["order[0][column]"], out order);
                string direction = Request["order[0][dir]"];
                var orderByColumns = new[] { "Id", "MinPayDiscount", "MaxPayDiscount", "DiscountProbability", "Action" };
                string search = Request["search[value]"];
                TableDataViewDto<ViewMatrixCloudProjectInfoDto> theList = MatrixCloudProjectInfoBLL.Instance.GetPagingList(draw, (start / length) + 1, length, SqlSafe(search),
                orderByColumns[order] + " " + direction);
                JsonResult jsonResult = Json(theList);
                jsonResult.MaxJsonLength = int.MaxValue;
                return jsonResult;
            }
            catch (Exception ex)
            {
                Logger.Error("SysConfigController ProjectInfoList Catch Error: " + ex.Message);
                return Json(false);
            }
        }

        public ActionResult ProjectInfoCreate()
        {
            return View();
        }
        [HttpPost]
        public ActionResult ProjectInfoCreate(MatrixCloudProjectInfo model)
        {
            var result = new Result(){ Status=false};
            var checkModel = MatrixCloudProjectInfoBLL.Instance.GetModelList("PjName='" + model.PjName + "'").FirstOrDefault();
            if (checkModel != null)
            {
                result.Message = "项目名称已存在，请更换";
                return Json(result);
            }
            var pjCode = MatrixCloudProjectInfoBLL.Instance.GetModelList("PjCode='" + model.PjCode + "'").FirstOrDefault();
            if (pjCode != null)
            {
                result.Message = "Code已存在，请更换";
                return Json(result);
            }
            var pjMcId = MatrixCloudProjectInfoBLL.Instance.GetModelList("pjMcId='" + model.PjMcId + "'").FirstOrDefault();
            if (pjMcId != null)
            {
                result.Message = "McId已存在，请更换";
                return Json(result);
            }
            var pjSecret = MatrixCloudProjectInfoBLL.Instance.GetModelList("PjSecret='" + model.PjSecret + "'").FirstOrDefault();
            if (pjSecret != null)
            {
                result.Message = "Secret已存在，请更换";
                return Json(result);
            }
            //model.PjCode = model.PjName;
            //model.PjMcId = ConvertHelper.getTimestamp();
           // model.PjSecret = EncryptionLib.Encrypt(model.PjCode + StringExtension.GenerateCheckCodeNum(10));
            model.AddTime = DateTime.Now;
            result.Status = MatrixCloudProjectInfoBLL.Instance.Add(model) > 0;
            if (result.Status == false)
            {
                result.Message = "添加失败，请重试";
            }
            return Json(result);
        }

        public string GetCode(string pjCode)
        {
            var checkModel = MatrixCloudProjectInfoBLL.Instance.GetModelList("PjCode='" + ConvertHelper.StrConvertToPinyin(pjCode) + "'").FirstOrDefault();
            if (checkModel != null)
            {
                pjCode += StringExtension.GenerateCheckCodeNum(4);
                GetCode(pjCode);
            }
            return ConvertHelper.StrConvertToPinyin(pjCode);
        }
        public ActionResult ProjectInfoUpdate(int id)
        {
            var model = MatrixCloudProjectInfoBLL.Instance.GetModel(id);
            return View(model ?? new MatrixCloudProjectInfo());
        }

        [HttpPost]
        public ActionResult ProjectInfoUpdate(MatrixCloudProjectInfo model)
        {
            var result = new Result();
            var checkModel = MatrixCloudProjectInfoBLL.Instance.GetModel(model.Id);
            if (checkModel != null && model.PjName != checkModel.PjName)
            {
                var smodel = MatrixCloudProjectInfoBLL.Instance.GetModelList("PjName='" + model.PjName + "'").FirstOrDefault();
                if (smodel != null)
                {
                    result.Message = "项目名称已存在，请更换";
                    return Json(result);
                }
            }
            if (checkModel != null && model.PjCode != checkModel.PjCode)
            {
                var smodel = MatrixCloudProjectInfoBLL.Instance.GetModelList("PjCode='" + model.PjCode + "'").FirstOrDefault();
                if (smodel != null)
                {
                    result.Message = "Code已存在，请更换";
                    return Json(result);
                }
            }
            if (checkModel != null && model.PjMcId != checkModel.PjMcId)
            {
                var smodel = MatrixCloudProjectInfoBLL.Instance.GetModelList("PjMcId='" + model.PjMcId + "'").FirstOrDefault();
                if (smodel != null)
                {
                    result.Message = "McId已存在，请更换";
                    return Json(result);
                }
            }
            if (checkModel != null && model.PjSecret != checkModel.PjSecret)
            {
                var smodel = MatrixCloudProjectInfoBLL.Instance.GetModelList("PjSecret='" + model.PjSecret + "'").FirstOrDefault();
                if (smodel != null)
                {
                    result.Message = "Secret已存在，请更换";
                    return Json(result);
                }
            }
            result.Status = MatrixCloudProjectInfoBLL.Instance.Update(model);
            if (result.Status == false)
            {
                result.Message = "修改失败，请重试";
            }
            return Json(result);
        }

        [HttpPost]
        public JsonResult MatrixCloudProjectInfoDeleteData()
        {
            var ids = Request["doIds"];
            var result = MatrixCloudProjectInfoBLL.Instance.DeleteList(ids);
            return Json(result);

        }

        [HttpPost]
        public ActionResult GetPjSecret(string pjCode)
        {
            var result = new Result();
            result.Status = true;
            result.Message = EncryptionLib.Encrypt(pjCode + StringExtension.GenerateCheckCodeNum(10));
            return Json(result);
        }
        #endregion
    }
}